package com.zhanghe.study;

import com.zhanghe.study.model.User;
import com.zhanghe.study.model.many2one.Customer;
import org.hibernate.*;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.hibernate.jdbc.ReturningWork;
import org.hibernate.jdbc.Work;
import org.hibernate.service.ServiceRegistry;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * @author zh
 * @date 2020/12/4 10:00
 */
public class Main {
    private static final SessionFactory sessionFactory;
    // 创建sessionFactory对象
    static {
        try {
            // 对应的hibernate基本配置信息和对象关系映射信息
            Configuration configuration = new Configuration();
            // 找的hibernate.cfg.xml配置文件
            configuration.configure();
            // 4.0之前不需要使用serviceRegistry  直接构建sessionFactory  configuration.buildSessionFactory()
            // 4.0之后创建serviceRegistry,所有的配置和服务都要在该对象中注册才可以生效
            // 4.3之前使用该方式new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    // 创建session对象
    public static Session getSession() throws HibernateException {
        return sessionFactory.openSession();
    }

    public static void main(final String[] args) throws Exception {
        final Session session = getSession();
        // 开启事务
        Transaction transaction = session.beginTransaction();
        try {
            testSave(session);
//            testPersist(session);

//            testGet(session);
//            testLoad(session);
//            testOid(session);
//            testEvict(session);
//                manyToOne(session);
//            testQuery(session);
//            testPage(session);
//            testFieldQuery(session);
//            testFieldQuery2(session);
//            testCriteria(session);
            transaction.commit();
        } catch (Exception e){
            transaction.rollback();
            e.printStackTrace();
        } finally {
            if(session != null && session.isOpen()){
                session.close();
            }
            if(sessionFactory != null && !sessionFactory.isClosed()){
                sessionFactory.close();
            }
        }
    }

    /**
     * 测试save方法
     * @param session
     */
    public static void testSave(Session session){
            User user = new User();
            user.setAge(18);
            user.setName("_&ng=__CTREF");
            user.setId(100);
            session.save(user);
    }

    /**
     * 测试persist方法
     * @param session
     */
    public static void testPersist(Session session){
        User user = new User();
        user.setAge(18);
        user.setName("李四");
        user.setId(100);
        session.persist(user);
    }

    /**
     * 测试get方法
     * @param session
     */
    public static void testGet(Session session){
        User user = (User) session.get(User.class,100);
        System.out.println(user);
    }

    /**
     * 测试load方法
     * @param session
     */
    public static void testLoad(Session session){
        User user = (User) session.load(User.class,1);
        System.out.println(user);
    }

    public static void testOid(Session session){
        User user = (User) session.get(User.class,1);
        System.out.println(user);
        User user1  = new User();
        user1.setId(1);
        user1.setName("王五");
        session.saveOrUpdate(user1);
    }

    public static void testEvict(Session session){
        User user = (User) session.get(User.class,1);
        user.setName("张三1");
        session.evict(user);
    }

    public static void testConnection(Session session){
        session.doWork(new Work() {
            @Override
            public void execute(Connection connection) throws SQLException {

            }
        });

        session.doReturningWork(new ReturningWork<Object>() {
            @Override
            public Object execute(Connection connection) throws SQLException {
                return null;
            }
        });
    }

    public static void manyToOne(Session session){
        Customer customer = new Customer();
    }

    /**
     * 使用参数位置
     * @param session
     */
    public static void testQuery(Session session){
        String hql = "from User where id > ?";
        List<User> users = session.createQuery(hql)
                .setInteger(0,2).list();
        System.out.println(users);

    }

    /**
     * 使用参数名称
     * @param session
     */
    public static void testQuery2(Session session){
        String hql = "from User where id > :id";
        List<User> users = session.createQuery(hql)
                .setInteger("id",2).list();
        System.out.println(users);
    }

    /**
     * 分页
     * @param session
     */
    public static void testPage(Session session){
        List<User> users = session.createQuery("from User")
                .setFirstResult(1)
                .setMaxResults(2).list();
        System.out.println(users);
    }

    /**
     * 查询部分字段
     * @param session
     */
    public static void testFieldQuery(Session session){
        List<Object[]> result = session.createQuery("select id,name from User").list();
        for(Object[] objs : result){
            System.out.println(Arrays.asList(objs));
        }
    }

    /**
     * 查询部分字段
     * @param session
     */
    public static void testFieldQuery2(Session session){
        List<User> result = session.createQuery("select new User(id,name) from User").list();
        for(User user : result){
            System.out.println(user);
        }
    }

    /**
     * 测试Criteria
     * @param session
     */
    public static void testCriteria(Session session){
        Criteria criteria = session.createCriteria(User.class);
        criteria.add(Restrictions.eq("id",2));
        User user = (User) criteria.uniqueResult();
        System.out.println(user);
    }

    /**
     * 测试Criteria
     * @param session
     */
    public static void testCriteria2(Session session){
        Criteria criteria = session.createCriteria(User.class);
        criteria.add(Restrictions.eq("id",2));
        User user = (User) criteria.uniqueResult();
        System.out.println(user);
    }



}